package com.hy.product.controller;

import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.ClusterFlowConfig;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
public class SentinelControllerBoolean {
    /**
     *  使用的API为SphO，限流后返回的值为boolean类型
     *
     * 注意：SphO.entry必须和SphO.exit成对出现 否则会报错
     * @return
     */
    @RequestMapping("/boolean")
    public boolean returnBoolean() {
        if (SphO.entry("Sentinel-boolean")){
            try {
                System.out.println("Hello Sentinel");
                return true;
            }finally {
                //  限流出口
                SphO.exit();
            }
        }else {
            //限流后进行的操作
            System.out.println("系统繁忙,请稍后再试");
            return false;
        }
    }


    /** 定义限流规则
     * @PostConstruct 此注解的含义是：本类构造方法执行结束后执行
     */
/*    @PostConstruct  //
    public void init2(){
        //1.创建存放限流规则的集合
        List<FlowRule> rules = new ArrayList<FlowRule>();

        //2.创建限流规则
        FlowRule flowRule = new FlowRule();
        flowRule.setClusterConfig(new ClusterFlowConfig());
        //定义资源，表示Sentinel会对哪个资源生效
        flowRule.setResource("Sentinel-boolean");
        //定义限流的类型(此处使用QPS作为限流类型)
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //定义QPS每秒通过的请求数
        flowRule.setCount(1);

        //3.将限流规则存放到集合中
        rules.add(flowRule);
        //4.加载限流规则
        FlowRuleManager.loadRules(rules);

    }*/
}
